<template>
  <div>
    <!-- 上传资源对话框 -->
    <el-dialog title="上传资源" :visible.sync="dialogVisible" width="500px" custom-class="upload-dialog"
      @close="handleClose">
      <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="80px">
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="uploadForm.name" placeholder="请输入资源名称" />
        </el-form-item>

        <el-form-item label="资源分类" prop="category">
          <el-select v-model="uploadForm.category" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.label"
              :value="category.value" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="资源类型" prop="isFree">
          <el-radio-group v-model="uploadForm.isFree">
            <el-radio :label="1">免费</el-radio>
            <el-radio :label="0">付费</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="存储类型" prop="storageType">
          <el-radio-group v-model="uploadForm.storageType">
            <el-radio :label="0">网盘存储</el-radio>
            <el-radio :label="1">本站存储</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="网盘地址" prop="panPath" v-if="uploadForm.storageType === 0">
          <el-input v-model="uploadForm.panPath" placeholder="请输入网盘地址" />
        </el-form-item>

        <el-form-item label="提取码" prop="panCode" v-if="uploadForm.storageType === 0">
          <el-input v-model="uploadForm.panCode" placeholder="请输入提取码" />
        </el-form-item>

<el-form-item label="资源文件" prop="file" v-if="uploadForm.storageType === 1">
  <el-upload 
    ref="upload" 
    :action="uploadAction"
    :on-success="handleUploadSuccess"
    :on-error="handleUploadError"
    :http-request="customUpload"
    :limit="1"
    :auto-upload="true"
    :show-file-list="true"
    :file-list="fileList">
    <el-button type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">请选择要上传的文件，文件夹请打包成压缩包格式上传</div>
  </el-upload>
</el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addResourceApi,uploadFileApi } from '@/api/resources';
export default {
  name: "AddResource",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    categories: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      uploading: false,
      uploadForm: {
        name: '',
        category: '',
        isFree: 1,
        storageType: 1,
        panPath: '',
        panCode: '',
        fileList: [],
        fileId: null,
        servePath:'',
      },
      uploadRules: {
        name: [
          { required: true, message: '请输入资源名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择资源分类', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择资源类型', trigger: 'change' }
        ],
        panPath: [
          { required: true, message: '请输入网盘地址', trigger: 'blur' }
        ],
        panCode: [
          { required: true, message: '请输入提取码', trigger: 'blur' }
        ],
  //       file: [
  //   { required: true, message: '请上传资源文件', trigger: 'change' }
  // ]
      }
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    }
  },
  methods: {

      /**
   * 文件上传的方法
   */
async customUpload(fileObj) {
  try {
    // Element UI 传递的是包含 file 属性的对象
    const file = fileObj.file; // 提取实际的 File 对象
    const response = await uploadFileApi(file);
    console.log(response);
    if(response.code === 200){
          this.uploadForm.fileId = 0;
          this.uploadForm.servePath = response.data;
    }

    return response;
  } catch (error) {
    this.$message.error('文件上传失败，请重试');
    console.error('文件上传错误:', error);
    throw error;
  }
},

      /**
   * 文件上传成功回调
   */
  handleUploadSuccess(response, file, fileList) {
    this.$message.success('文件上传成功');
    // 假设后端返回了 fileId 或 url
    // this.uploadForm.fileId = response.data.fileId; // 示例：保存文件标识
    // this.fileList = fileList; // 更新文件列表
  },

  /**
   * 文件上传失败回调
   */
  handleUploadError(error, file, fileList) {
    this.$message.error('文件上传失败，请重试');
    console.error('文件上传错误:', error);
  },
  
 
    /**
     * 关闭对话框
     */
    handleClose() {
      this.dialogVisible = false;
      this.$refs.uploadForm.resetFields();
    },
    /**
     * 提交上传
     */
    submitUpload() {
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          addResourceApi(this.uploadForm).then(res => {
            this.$message.success("资源上传成功，等待博主审核！");
            // 重置表单
            this.$refs.uploadForm.resetFields();
            this.handleClose();
          })
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">

</style>
